package com.flyduck.web;

import com.flyduck.vo.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.aspectj.apache.bcel.classfile.Unknown;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: flyduck-admin
 * @description:
 * @author: flyduck
 * @create: 2020-05-08 22:33
 **/
@Controller
public class LoginController {

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Subject currentUser = SecurityUtils.getSubject();
            //未认证登录
            if(!currentUser.isAuthenticated()) {
                //密码进行MD5加密
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
                //认证登陆
                currentUser.login(usernamePasswordToken);
            }
            ajaxResult.setSuccess(true);
            ajaxResult.setMsg("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("账号不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("密码错误");
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("未知错误");
        }
        return ajaxResult;

    }


}
